package dlvwrapper;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import dinnerSimulation.Coord;



public class DlvWrapper {
	 
    private ProcessBuilder launcher;
    private Process process;
    private BufferedReader output;
    private File dlvDir;
    private String dlvExe;
	
	
	public DlvWrapper(){
	}
	
	// Ciccio : stanza e posizione
	// Oggetto: nome, stanza e posizione
	// nome subplan
	public List<Coord> getPlan(String subPlan) {
        
        try {
                launcher = new ProcessBuilder();
                Map<String, String> environment = launcher.environment();
                launcher.redirectErrorStream(true);
                dlvDir = new File("dlv");
                launcher.directory(dlvDir);
                environment.put("name", "var");
               dlvExe = dlvDir.getAbsolutePath() + "\\dlv.mingw.exe";
               // dlvExe = dlvDir.getAbsolutePath() + "/dlv";// linux
  
        } catch (Exception e) {
                System.err.println(e.getCause());
        }
        
        String outputText = "";
        Integer planLength = 0;
        boolean planFounded = false;
        List<Coord> moves = new ArrayList<Coord>();
        
        

         try{
                    // Create file 
                        
                 /*   FileWriter fstream = new FileWriter("dlv/ciccioP.initial.plan");
                    BufferedWriter out = new BufferedWriter(fstream);
                    out.write("%Hello Java\n");
                    out.write("initially: at(ciccio,"+ciccioRoom+","+ciccioPos+"). " +
                    					"at("+object+","+objRoom+","+objPos+")."
                              );
                        
                    out.close();*/
                    }catch (Exception e){//Catch exception if any
                      System.err.println("Error: " + e.getMessage());
         }
         
         
        while(!planFounded){
                try {
                        
                        
                        launcher.command(dlvExe, "-FP", subPlan+".plan", "ciccio_pasticcio_initial.plan", "ciccio_pasticcio_back.dl",
                                        "-N=100", "-planlength=" + planLength.toString());
                        process = launcher.start();
                        
                        if (process != null) {                                  
                                //System.out.println("****DLV STARTED****");                                    
                                output = new BufferedReader(new InputStreamReader(
                                                process.getInputStream()));
                                String line = new String();
                                OutputStream stdin = process.getOutputStream();
                                outputText = new String();
                                while ((line = output.readLine()) != null ) {
                                        if (line.contains("Check")) {                                                   
                                                stdin.write(("y\n").getBytes());
                                                stdin.flush();
                                                if (line.contains("is secure")) {
                                                        outputText += "the plan is secure\n";
                                                        planFounded = true;
                                                        //System.out.println((System.currentTimeMillis()-elapsedTime)/1000 + " seconds to compute plan");
                                                        
                                                        break;
                                                } else { //plan's not secure
                                                        stdin.write(("n\n").getBytes());
                                                        stdin.flush();
                                                        break;
                                                }
                                        } else {
                                                stdin.write(("n\n").getBytes());
                                                stdin.flush();
                                        }
                                        outputText += line+"\n";                                        
                                         
                                }//end inner while
                        }

                } catch (IOException e) {
                        System.err.println(e.getCause());
                }
                catch (java.lang.ArrayIndexOutOfBoundsException e) {
					System.out.print("Errore nei file per dlv.");
					 JOptionPane.showMessageDialog(null,"Input Error.", "Input Error",
			                    JOptionPane.ERROR_MESSAGE );
				}
                if(!planFounded){
                        if(planLength > 50){
                                planFounded = true;
                        } else {
                                planLength++;
                        }
                }
        }//end extern while
        

        outputText += "planlength " + Integer.toString(planLength);

        String[] temp = outputText.split("PLAN: ");
        try {
			System.out.println("PLAN: " + temp[1]);
			
		} catch (java.lang.ArrayIndexOutOfBoundsException e1) {
			// TODO Auto-generated catch block
			System.out.println("No Plan.");
			 JOptionPane.showMessageDialog(null,"No Plan.", "No Plan",
	                    JOptionPane.ERROR_MESSAGE );
			 this.process.destroy();
		}
        String temp2[]; 
//        System.out.println("temp2[0]" + temp2[0]);
//        System.out.println("temp2[1]" + temp2[1]);
		try {
			temp2 = temp[1].split("; ");
		
        
        
    
        int j = 0;
        boolean subGoal= false;
        for (int i = 0; i < temp2.length && !subGoal; i++) {
        	if (temp2[i].startsWith(subPlan))
        		subGoal = true;
        	
                if(temp2[i].startsWith("move") && !temp2[i].contains("no action")){
   
                    String[] coord = temp2[i].split("\b"); // coord = x,y)  
                   // System.out.println("coord[0] " + coord[0]);
                    //System.out.println("coord[1] " + coord[1]);
                    //System.out.println("coord[0].length " + coord[0].length());
                    String sub  = coord[0].substring(coord[0].length()-4);
                    System.out.println("x = "+ sub);
                    int x=0;
					try {
						x = Integer.parseInt(""+sub.charAt(0)) -1;
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						System.err.println("Irregolarit� nel piano");
					     JOptionPane.showMessageDialog(null,"Irregolarit� nel piano", "Irregolarit� nel piano",
                                 JOptionPane.ERROR_MESSAGE );

					}
                    int y = Integer.parseInt(""+sub.charAt(2)) -1;
                    Coord nCoord = new Coord(x, y); 
                	moves.add(j++, nCoord);
                }
        }
        
} catch ( java.lang.ArrayIndexOutOfBoundsException e) {
			System.out.println("No Plan.");
			System.err.println("Irregolarit� nel piano");
		     JOptionPane.showMessageDialog(null,"No Plan.", "No Plan",
                    JOptionPane.ERROR_MESSAGE );
		}
 
//      System.out.println("----PLAN----");
//      for(Integer i:moves)
//              System.out.print(i +" ");
//      System.out.println();
        
        return moves;
}
}
